package cn.com.hhrcw.web;

import cn.com.hhrcw.entity.*;
import cn.com.hhrcw.mapstruct.*;
import cn.com.hhrcw.params.NewResumeParams;
import cn.com.hhrcw.service.*;
import cn.com.hhrcw.utils.SubjectUtils;
import cn.com.hhrcw.vo.*;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.utils.UuidUtils;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;


import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 简历-简历-新建
 */
@RestController
@Slf4j
@RequestMapping("/personal/v1/newResume")
@Api(tags = "简历-简历本历")
public class NewResumeController extends JeecgController<NewResume, NewResumeService> {

    //region Description
    @Autowired
    private NewResumeService newResumeService;

    @Autowired
    private CvResumeConvert cvResumeConvert;

    @Autowired
    private NewUserInfoService newUserInfoService;

    @Autowired
    private NewWorkIntentionService newWorkIntentionService;

    @Autowired
    private NewEduInfoService newEduInfoService;

    @Autowired
    private NewWorkInfoService newWorkInfoService;

    @Autowired
    private NewProjectInfoService newProjectInfoService;

    @Autowired
    IPiInfoService piInfoService;

    @Autowired
    ICvResumeService resumeService;

    @Autowired
    private ICvWorkIntentionService cvWorkIntentionService;

    @Autowired
    private ICvUserWorkInfoService cvUserWorkInfoService;

    @Autowired
    private ICvUserEduInfoService cvUserEduInfoService;

    @Autowired
    private ICvProjectInfoService cvProjectInfoService;

    @Autowired
    private ICvTrainService cvTrainService;

    @Autowired
    private ICvLanguageLevelService cvLanguageLevelService;

    @Autowired
    private ICvSkillsService cvSkillsService;


    @Autowired
    private ICvCertificateService cvCertificateService;

    @Autowired
    private IFileService fileService;

    @Autowired
    private ICvFamilyMemberService cvFamilyMemberService;
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private CvFamilyMemberConvert cvFamilyMemberConvert;

    @Autowired
    private CvWorkIntentionConvert enCvWorkIntentionConvert;
    @Autowired
    private CvUserWorkInfoConvert enCvUserWorkInfoConvert;
    @Autowired
    private CvUserEduInfoConvert enCvUserEduInfoConvert;
    @Autowired
    private CvProjectInfoConvert enCvProjectInfoConvert;
    @Autowired
    private CvTrainConvert enCvTrainConvert;
    @Autowired
    private CvLanguageLevelConvert enCvLanguageLevelConvert;
    @Autowired
    private CvSkillsConvert skillsConvert;
    @Autowired
    private CvCertificateConvert certificateConvert;

    @Autowired
    private ICvTimeDurationCompareService cvTimeDurationCompareService;

    @Autowired
    EnterpriseService enterpriseService;

    @Autowired
    private AddNewResumeService addNewResumeService;
    /**
     * 新简历添加
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/add")
    @AutoLog("新简历添加")
    @ApiOperation(value = "添加", notes = "添加")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> add(@RequestBody @Valid NewResumeParams params) {
        Date date = DateUtil.date();
        SysUser sysUser = (SysUser) SubjectUtils.getSubject();
        String userId = sysUser.getId();
        // 查询该用户是否有简历
//        LambdaQueryWrapper<NewResume> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(NewResume::getDelFlag, false).eq(NewResume::getUserId, userId);
//        Integer hasResume = newResumeService.count(queryWrapper);
//        if (hasResume > 0) {
//            // 有简历，直接成功
//            //return Result.ok("成功");
//            //默认更新最新一条简历信息
//
//        }

        //查询该用户是否有简历
           /* List<NewResume> newResumes = newResumeService.lambdaQuery().eq(NewResume::getUserId, sysUser.getId()).eq(NewResume::getDelFlag, false).orderByDesc(NewResume::getCreateTime).list();
            if(newResumes.size() > 0) {
                //1、简历更新
                NewResume newResume = newResumes.get(0);
                newResume.setCreateTime(date);
                newResume.setCreateBy(userId);
                newResume.setDelFlag(false);
                newResume.setUserId(userId);
                newResume.setResumeName(params.getUsername() + "的附件简历");
                newResume.setEnclosureId(params.getEnclosureId());
                newResumeService.updateById(newResume);
                // 2、基本信息更新
                List<NewUserInfo> newUserInfos = newUserInfoService.lambdaQuery().eq(NewUserInfo::getId, sysUser.getId()).eq(NewUserInfo::getDelFlag, false).orderByDesc(NewUserInfo::getCreateTime).list();
                if (newUserInfos.size() > 0) {
                    NewUserInfo newUserInfo = newUserInfos.get(0);
                    newUserInfo.setDelFlag(false);
                    newUserInfo.setCreateTime(date);
                    newUserInfo.setCreateBy(userId);
                    newUserInfo.setAddress(params.getAddress());
                    newUserInfo.setUsername(params.getUsername());
                    newUserInfo.setSex(params.getSex());
                    newUserInfo.setAge(params.getAge());
                    newUserInfo.setPhone(params.getPhone());
                    newUserInfo.setPhotoId(params.getPhotoId());
                    newUserInfoService.updateById(newUserInfo);
                }
                // 3、期望岗位更新
                List<NewWorkIntention> newWorkIntentions = newWorkIntentionService.lambdaQuery().eq(NewWorkIntention::getResumeId, newResume.getId()).orderByDesc(NewWorkIntention::getCreateTime).list();
                if (newWorkIntentions.size() > 0) {
                    NewWorkIntention newWorkIntention = newWorkIntentions.get(0);
                    newWorkIntention.setDelFlag(false);
                    newWorkIntention.setCreateTime(date);
                    newWorkIntention.setCreateBy(userId);
                    newWorkIntention.setWorkNatureName(params.getWorkNatureName());
                    newWorkIntention.setJobId(params.getJobId());
                    newWorkIntention.setChannel(params.getChannel());
                    newWorkIntention.setResumeId(newResume.getId());
                    newWorkIntentionService.updateById(newWorkIntention);
                }
                // 4、教育经历更新
                List<NewEduInfo> newEduInfos = newEduInfoService.lambdaQuery().eq(NewEduInfo::getResumeId, newResume.getId()).orderByDesc(NewEduInfo::getCreateTime).list();
                if (newEduInfos.size() > 0) {
                    NewEduInfo newEduInfo = newEduInfos.get(0);
                    newEduInfo.setDelFlag(false);
                    newEduInfo.setCreateTime(date);
                    newEduInfo.setCreateBy(userId);
                    newEduInfo.setEduLevel(params.getEduLevel());
                    newEduInfo.setSchoolName(params.getSchoolName());
                    newEduInfo.setEndEduTime(params.getEndEduTime());
                    newEduInfo.setMajor(params.getMajor());
                    newEduInfo.setResumeId(newResume.getId());
                    newEduInfoService.updateById(newEduInfo);
                }
                // 5、工作经历更新
                List<NewWorkInfo> newWorkInfos = newWorkInfoService.lambdaQuery().eq(NewWorkInfo::getResumeId, newResume.getId()).orderByDesc(NewWorkInfo::getCreateTime).list();
                if (newWorkInfos.size() > 0) {
                    NewWorkInfo newWorkInfo = newWorkInfos.get(0);
                    newWorkInfo.setDelFlag(false);
                    newWorkInfo.setCreateTime(date);
                    newWorkInfo.setCreateBy(userId);
                    newWorkInfo.setCompanyName(params.getCompanyName());
                    newWorkInfo.setPositionNameStr(params.getPositionNameStr());
                    newWorkInfo.setWorkContent(params.getWorkContent());
                    newWorkInfo.setWorkStartTime(params.getWorkStartTime());
                    if(StringUtils.isNotBlank(params.getWorkEndTime())) {
                        newWorkInfo.setWorkEndTime(params.getWorkEndTime());
                    }
                    newWorkInfo.setResumeId(newResume.getId());
                    newWorkInfoService.updateById(newWorkInfo);
                }
                //  6、项目经历更新
                List<NewProjectInfo> newProjectInfos = newProjectInfoService.lambdaQuery().eq(NewProjectInfo::getResumeId, newResume.getId()).orderByDesc(NewProjectInfo::getCreateTime).list();
                if (newProjectInfos.size() > 0) {
                    NewProjectInfo newProjectInfo = newProjectInfos.get(0);
                    newProjectInfo.setDelFlag(false);
                    newProjectInfo.setCreateTime(date);
                    newProjectInfo.setCreateBy(userId);
                    newProjectInfo.setProjectDescribe(params.getProjectDescribe());
                    newProjectInfo.setResumeId(newResume.getId());
                    newProjectInfoService.updateById(newProjectInfo);
                }
                return Result.ok("成功");
            }*/
        //查询该用户是否有简历，现有逻辑，是否有简历都新增
        List<NewResume> newResumes = newResumeService.lambdaQuery().eq(NewResume::getUserId, sysUser.getId()).eq(NewResume::getDelFlag, false).orderByDesc(NewResume::getCreateTime).list();

        // 1、简历添加
//        NewResume newResume = new NewResume();
//        newResume.setCreateTime(date);
//        newResume.setCreateBy(userId);
//        newResume.setDelFlag(false);
//        newResume.setUserId(userId);
//        newResume.setResumeName(params.getUsername() + "的附件简历");
//        newResume.setEnclosureId(params.getEnclosureId());
//        newResumeService.save(newResume);
//
//        // 2、基本信息添加,基本信息保持一条
//        NewUserInfo newUserInfo = new NewUserInfo();
//        newUserInfo.setDelFlag(false);
//        newUserInfo.setCreateTime(date);
//        newUserInfo.setCreateBy(userId);
//        newUserInfo.setAddress(params.getAddress());
//        newUserInfo.setUsername(params.getUsername());
//        newUserInfo.setSex(params.getSex());
//        newUserInfo.setAge(params.getAge());
//        newUserInfo.setPhone(params.getPhone());
//        newUserInfo.setPhotoId(params.getPhotoId());
//        newUserInfoService.save(newUserInfo);
//
//        // 3、期望岗位添加
//        NewWorkIntention newWorkIntention = new NewWorkIntention();
//        newWorkIntention.setDelFlag(false);
//        newWorkIntention.setCreateTime(date);
//        newWorkIntention.setCreateBy(userId);
//        newWorkIntention.setWorkNatureName(params.getWorkNatureName());
//        newWorkIntention.setJobId(params.getJobId());
//        newWorkIntention.setChannel(params.getChannel());
//        newWorkIntention.setResumeId(newResume.getId());
//        newWorkIntentionService.save(newWorkIntention);
//
//        // 4、教育经历添加
//        NewEduInfo newEduInfo = new NewEduInfo();
//        newEduInfo.setDelFlag(false);
//        newEduInfo.setCreateTime(date);
//        newEduInfo.setCreateBy(userId);
//        newEduInfo.setEduLevel(params.getEduLevel());
//        newEduInfo.setSchoolName(params.getSchoolName());
//        newEduInfo.setEndEduTime(params.getEndEduTime());
//        newEduInfo.setMajor(params.getMajor());
//        newEduInfo.setResumeId(newResume.getId());
//        newEduInfoService.save(newEduInfo);
//
//        // 5、工作经历添加
//        NewWorkInfo newWorkInfo = new NewWorkInfo();
//        newWorkInfo.setDelFlag(false);
//        newWorkInfo.setCreateTime(date);
//        newWorkInfo.setCreateBy(userId);
//        newWorkInfo.setCompanyName(params.getCompanyName());
//        newWorkInfo.setPositionNameStr(params.getPositionNameStr());
//        newWorkInfo.setWorkContent(params.getWorkContent());
//        newWorkInfo.setWorkStartTime(params.getWorkStartTime());
//        if(StringUtils.isNotBlank(params.getWorkEndTime())) {
//            newWorkInfo.setWorkEndTime(params.getWorkEndTime());
//        }
//        newWorkInfo.setResumeId(newResume.getId());
//        newWorkInfoService.save(newWorkInfo);
//
//        //  6、项目经历添加
//        NewProjectInfo newProjectInfo = new NewProjectInfo();
//        newProjectInfo.setDelFlag(false);
//        newProjectInfo.setCreateTime(date);
//        newProjectInfo.setCreateBy(userId);
//        newProjectInfo.setProjectDescribe(params.getProjectDescribe());
//        newProjectInfo.setResumeId(newResume.getId());
//        newProjectInfoService.save(newProjectInfo);

        return Result.ok("成功");
    }
    /**
     * 新简历添加
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/addNew")
    @AutoLog("新简历添加")
    @ApiOperation(value = "添加", notes = "添加")
    public Result<?> addNew(@RequestBody @Valid NewResumeParams params) {
        SysUser sysUser = (SysUser) SubjectUtils.getSubject();
        String userId = sysUser.getId();
        //应急，不校验，直接添加
        //先校验
        LambdaUpdateWrapper<CvResume> wrapper = Wrappers.lambdaUpdate();
        wrapper.eq(CvResume::getLanType, "0").eq(CvResume::getUserId, userId)
                .eq(CvResume::getType, "0").eq(CvResume::getResumeType,"2")
                .eq(CvResume::getDelFlag, false);
        List<CvResume> list = resumeService.list(wrapper);
        if (!CollectionUtils.isEmpty(list)) {
            return Result.error("已有简历，无需再次添加");
        }

        addNewResumeService.saveNewResume(params,userId);
//        boolean isRepeat = cvTimeDurationCompareService.isTimeDurationRepeat(ExperienceTypeEnum.EDUCATION.getValue(),
//                sysUser.getId(),cvUserEduInfo.getResumeId(),false,null,cvUserEduInfo.getStartEduTime(),cvUserEduInfo.getEndEduTime());
//        if(isRepeat) return Result.error("操作失败，请检查开始时间和结束时间");
        String resumeInfo = resumeService.getResumeInfo(sysUser.getId(), 0, null);
        String resumePdfInfo = resumeService.getResumeInfoPDF(sysUser.getId(), 0, null);

        return Result.ok("成功");
    }

    @GetMapping("/getResumeInfoByUserId")
    public Result<NewResumeInfoVO> getResumeInfo(String resumeId) {
        NewResumeInfoVO result = new NewResumeInfoVO();

        NewResume newResume = newResumeService.getById(resumeId);
        if (newResume == null) {
            return null;
        }
        String userId = newResume.getUserId();
       //1、简历信息表
        result.setNewResume(newResume);
        SysUser sysUser = sysUserService.getById(newResume.getUserId());
        //1、个人基本信息
        List<NewUserInfo> newUserInfos = newUserInfoService.lambdaQuery().eq(NewUserInfo::getCreateBy, sysUser.getId()).eq(NewUserInfo::getDelFlag, false).orderByDesc(NewUserInfo::getCreateTime).list();
        if(newUserInfos.size()>0) {
            result.setNewUserInfo(newUserInfos.get(0));
        }

        // 4、教育经历更新
        List<NewEduInfo> newEduInfos = newEduInfoService.lambdaQuery().eq(NewEduInfo::getResumeId, newResume.getId()).orderByDesc(NewEduInfo::getCreateTime).list();
        if(newEduInfos.size()>0) {
            result.setNewEduInfo(newEduInfos.get(0));
        }


        return Result.ok(result);
    }

    @GetMapping("/queryById")
    public Result<NewResumeInfosVO> queryNewResumeInfoVO(String userId) {
        NewResumeInfosVO result = new NewResumeInfosVO();

        List<CvResume> cvResumeList = resumeService
                .lambdaQuery()
                .eq(CvResume::getUserId, userId)
                .eq(CvResume::getDelFlag, false)
                .orderByDesc(CvResume::getCreateTime)
                .list();
        if (cvResumeList.size() <= 0) {
            throw new JeecgBootException("数据不存在");
        }else {
            //附件信息
            List<File> files=new ArrayList<>();
            if (StringUtils.isNotBlank(cvResumeList.get(0).getEnclosureId())){
                String[] strings = cvResumeList.get(0).getEnclosureId().split(",");
                for (String string : strings) {
                    File file = fileService.getById(string);
                    if (null != file){
                        files.add(file);
                    }
                }

            }
            result.setFiles(files);
        }
        //1、简历信息表
        result.setNewResume(cvResumeList.get(0));

        //1、个人基本信息
        List<PiInfo> piInfoList = piInfoService.lambdaQuery().eq(PiInfo::getUserId,userId).eq(PiInfo::getDelFlag, false).orderByDesc(PiInfo::getCreateTime).list();
        if (piInfoList.size() <= 0) {
            throw new JeecgBootException("基本信息数据不存在");
        }
        result.setNewUserInfo(piInfoList.get(0));

        // 4、教育经历更新
        List<CvUserEduInfo> cvUserEduInfoList = cvUserEduInfoService.lambdaQuery().eq(CvUserEduInfo::getUserId,userId).eq(CvUserEduInfo::getDelFlag, false).orderByDesc(CvUserEduInfo::getCreateTime).list();
        if (cvUserEduInfoList.size() <= 0) {
            throw new JeecgBootException("教育经历数据不存在");
        }
        result.setNewEduInfo(cvUserEduInfoList.get(0));
        return Result.ok(result);
    }
    /**
     * 简历编辑
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/edit")
    @ApiOperation(value = "编辑", notes = "编辑")
    public Result<?> edit(@RequestBody @Valid NewResumeParams params) {
        Date date = DateUtil.date();
        SysUser sysUser = (SysUser) SubjectUtils.getSubject();
        String userId = sysUser.getId();
        // 1、简历添加
        CvResume cvResume = new CvResume();
        cvResume.setUpdateTime(date);
        cvResume.setUpdateBy(userId);
        cvResume.setResumeName(params.getUsername() + "的附件简历");
        cvResume.setEnclosureId(params.getEnclosureId());
        cvResume.setId(params.getId());
        resumeService.updateById(cvResume);

        // 2、基本信息添加,基本信息保持一条
        PiInfo piInfo = new PiInfo();
        piInfo.setUpdateTime(date);
        piInfo.setUpdateBy(userId);
        piInfo.setName(params.getName());
        piInfo.setSex(params.getSex());
        piInfo.setPhone(params.getPhone());
        piInfo.setBirthday(params.getBirthday());
        piInfo.setHomeTown(params.getHomeTownCode());
        piInfo.setUsername(params.getUsername());
        piInfo.setId(params.getId());
        piInfoService.updateById(piInfo);

        // 4、教育经历添加
        CvUserEduInfo cvUserEduInfo = new CvUserEduInfo();
        cvUserEduInfo.setUpdateTime(date);
        cvUserEduInfo.setUpdateBy(userId);
        cvUserEduInfo.setEduLevel(params.getEduLevel());
        cvUserEduInfo.setR1(params.getR1());
        cvUserEduInfo.setSchoolName(params.getSchoolName());
        cvUserEduInfo.setEndEduTime(params.getEndEduTime());
        cvUserEduInfo.setStartEduTime(params.getStartEduTime());
        cvUserEduInfo.setMajor(params.getMajor());
        cvUserEduInfo.setId(params.getId());
        boolean updated = cvUserEduInfoService.updateById(cvUserEduInfo);

        return updated ? Result.ok() : Result.error("编辑失败");
    }

}
